package com.atguigu.yygh.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.yygh.dictListern.dictListern;
import com.atguigu.yygh.mapper.DictMapper;
import com.atguigu.yygh.model.cmn.Dict;
import com.atguigu.yygh.service.DictService;
import com.atguigu.yygh.vo.cmn.DictEeVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Autowired
    private DictMapper dictMapper;

    //1.根据数据id查询子数据列表
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    //根据方法对其返回结果进行缓存，下次请求时，如果缓存存在，则直接读取缓存数据返回；
    // 如果缓存不存在，则执行方法，并把返回的结果存入缓存中。一般用在查询方法上。
    //注意本地没有装redis，所以你要装才能运行，还有application.yml中的配置要对应
    //下一步就是你可以在其他地方加上你的缓存，柯美了，
    @Override
    public List<Dict> findChlidData(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        List<Dict> dictList = baseMapper.selectList(wrapper);
        //像list集合中每个dict对象设置children值
        for (Dict dict:dictList) {
            Long dictId = dict.getId();
            boolean b = this.isChildren(dictId);
            dict.setHasChildren(b);
        }
        return dictList;
    }

    //1.1判断id下面是否有字节点
    public boolean isChildren(Long id){
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        Integer count = baseMapper.selectCount(wrapper);
        return count>0;
    }

    //2.导出数据字典接口
    @Override
    public void exportData(HttpServletResponse response) {
        //设置下载信息
            try {
                response.setContentType("application/vnd.ms-excel");
                response.setCharacterEncoding("utf-8");
                // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
                String fileName = null;
                fileName = URLEncoder.encode("数据字典", "UTF-8");
                response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
                List<Dict> dictList = dictMapper.selectList(null);
                List<DictEeVo> dictVoList = new ArrayList<>(dictList.size());
                for(Dict dict : dictList) {
                    DictEeVo dictVo = new DictEeVo();
                    BeanUtils.copyProperties(dict, dictVo);
                    dictVoList.add(dictVo);
                }
                EasyExcel.write(response.getOutputStream(),DictEeVo.class).sheet("dict")
                        .doWrite(dictVoList);
            } catch (Exception e) {
                e.printStackTrace();
            }
    }



    //3.导入数据字典接口,实现这个必须要有监听器在dictListern中
    /**
     * 导入
     * allEntries = true: 方法调用后清空所有缓存
     * @param file
     */
    @CacheEvict(value = "dict", allEntries=true)
    @Override
    public void importData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,new dictListern(dictMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}
